package com.example.common.utils.upload;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;


@Slf4j
public class FileUploadUtils {

    private HttpServletRequest request;
    private String uploadPath;
    private long maxSize; // 最大文件大小（单位：字节）
    private List<String> allowedTypes; // 允许的文件类型

    public FileUploadUtils(HttpServletRequest request, String uploadPath, long maxSize, List<String> allowedTypes) {
        this.request = request;
        this.uploadPath = uploadPath;
        this.maxSize = maxSize;
        this.allowedTypes = allowedTypes;
    }


    public Map<String, Object> upload(MultipartFile file) throws IOException {
        // 检查文件类型
        String mimeType = file.getContentType();
        log.info("文件类型：{}", mimeType);
        if (!isFileTypeAllowed(mimeType)) {
            throw new IllegalArgumentException("文件类型不支持");
        }

        // 检查文件大小
        if (file.getSize() > maxSize) {
            throw new IllegalArgumentException(String.format("文件大小超出限制（文件大小：%s，允许大小：%s）", file.getSize(), maxSize));
        }

        // 生成唯一的文件名
        String fileName = UUID.randomUUID().toString() + "." + FilenameUtils.getExtension(file.getOriginalFilename());

        // 确保上传目录存在
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }

        // 构建完整的文件路径
        File destinationFile = new File(uploadDir, fileName);

        // 保存文件
        file.transferTo(destinationFile);
        
        Map<String, Object> res = new HashMap<String, Object>(){{
            put("fileName", fileName);
            put("filePath", destinationFile.getAbsolutePath());
            put("fileSize", file.getSize());
            put("fileType", file.getContentType());
            put("fileSuffix", fileName.substring(fileName.lastIndexOf('.') + 1));
        }};

        return res;
    }


    // 定义合法文件路径的正则表达式
    private static final String FILE_PATH_REGEX = "/^[a-zA-Z];[///]((?! )(?![^///]*/s+[///])[/w -]+[///])*(?! )(?![^.]+/s+/.)[/w -]+$/;";

    // 验证文件路径是否合法
    public static boolean isValidFilePath(String filePath) {
        
        /*
        // 检查文件路径是否包含非法字符
        Pattern pattern = Pattern.compile(FILE_PATH_REGEX);
        Matcher matcher = pattern.matcher(filePath);
        if (!matcher.matches()) {
            return false;
        }*/
        Path path = Paths.get(filePath).normalize();
        // 使用 Path 检查路径是否存在对应文件
        return path.toFile().exists();
    }


    // 删除文件的方法
    public static boolean removeFile(String filePath) {
        // 验证文件路径是否合法
        if (!isValidFilePath(filePath)) {
            throw new IllegalArgumentException("文件路径不合法");
        }

        // 检查文件是否存在
        File file = new File(filePath);
        if (!file.exists()) {
            throw new IllegalArgumentException("文件不存在");
        }

        // 删除文件
        boolean isDeleted = file.delete();
        if (!isDeleted) {
            throw new IllegalArgumentException("文件删除失败");
        }

        return true;
    }

    private boolean isFileTypeAllowed(String mimeType) {
        return allowedTypes.contains(mimeType);
    }
    
}
